package util;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author：fish
 * @Date：2023/4/3 10:28
 */
public class DBUtils {
    private static volatile MysqlDataSource mysqlDataSource;

    private static MysqlDataSource getMysqlDataSource() {
        if (mysqlDataSource == null) {
            synchronized (DBUtils.class) {
                if (mysqlDataSource == null) {
                    mysqlDataSource = new MysqlDataSource();
                    //mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/myblog2023?characterEncoding=utf8&useSSL=true");
                    mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/myblog2023?characterEncoding=utf8&useSSL=false");
                    mysqlDataSource.setUser("root");
                    mysqlDataSource.setPassword("Wwt@200288");
//                    mysqlDataSource.setPassword("12345678");
                }
            }
        }
        return mysqlDataSource;
    }

    /**
     * 有两种模式（单例模式的 Connection / 多例模式 Connection）
     * 此方法实现多例模式
     * @return
     */
    public static Connection getConnection() throws SQLException {
        //getConnection要处理一个异常再进行强转
        Connection connection =  getMysqlDataSource().getConnection();
        return connection;
    }

    public static void close(ResultSet resultSet, PreparedStatement statement, Connection connection) throws SQLException {
        if (resultSet != null) resultSet.close();
        if (statement != null) statement.close();
        if (connection != null) connection.close();
    }
}
